import { Component, PropTypes } from 'labrador-immutable';
import immutable from 'seamless-immutable';
//import { connect } from 'labrador-redux';

class Download extends Component {

  state = {
    images: [],
    selectedCount: 0
  }

  constructor(props) {
    super(props);
    this.state = immutable({});
  }

  children() {
    return {};
  }

  onLoad(options) {
    const images = JSON.parse(options.images);
    const imageCollection = Array.from(images, image => {
      return {
        checked: false,
        image
      }
    })
    this.setState({ images: imageCollection });
  }

  checkedImage(e) {
    const index = e.currentTarget.dataset.index;
    let { images } = this.state;
    let item = images[e.currentTarget.dataset.index];
    item = item.set('checked', ! item.checked);
    images = images.set(index, item);
    var count = 0;
    images.map(item => {
      if (item.checked) {
        count ++;
      }
      return;
    })
    this.setState({ images, selectedCount: count });
  }

  checkAllImages() {
    let { selectedCount, images } = this.state;
    const allChecked = images.length === selectedCount;
    let newImages = [];
    images.map(item => {
      newImages.push(item.set('checked', ! allChecked));
    });
    this.setState({ images: newImages, selectedCount: allChecked ? 0 : images.length });
  }

  downloadImages() {
    if (this.state.imageProcess > 0) {
      return
    }
    if (this.state.selectedCount === 0) {
      wx.showToast({
        title:'请选择图片～',
        duration:1000
      });
      return;
    }
    this.setState({ imageProcess: 1 });
    let images = [];
    this.state.images.map(item => {
      if (item.checked) {
        images.push(item.image);
      }
      return true;
    });
    this.checkSetting(() => {
      this.downloadImage(0, images);
    })
  }

  downloadImage(index, images) {
    if (index >= images.length) {
      return;
    }
    var that = this;
    const currentUrl = images[index];
    const downloadTask = wx.downloadFile({
      url: currentUrl,
      success: (res) => {
      },
      fail: function(err) {
      },
      complete: function(res) {
        if (res.statusCode === 200) {
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success(res) {
              that.downloadImage(index + 1, images);
              if (index === images.length - 1) {
                wx.showToast({
                  title:'下载完成～',
                  duration:1000
                });
                that.setState({ imageProcess: 0 })
              }
            },
            fail(err) {
              wx.showToast({
                title:err.errMsg,
                duration:1000
              });
            }
          })
        }
      }
    });
    const completeProcess = 100 * index;
    downloadTask.onProgressUpdate((res) => {          
      this.setState({ imageProcess: parseInt((completeProcess + res.progress)/images.length) });
    })
  }

  checkSetting(callback) {
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              callback()
            }
          })
        } else {
          callback()
        }
      }
    })
  }

}

export default Download;

// export default connect(
//   (state)=>({})
// )(Download);
